package game

import (
	"encoding/json"
	"fmt"

	"gitee.com/shiwjlinux/game-manager/client"
	"github.com/sirupsen/logrus"
)

var (
	Address = "http://172.20.12.12:9001"
	URL     = "/v1/ant_asset/games_list"
)

func GetAListOfGames() (*GameSet, error) {
	client := client.NewClient(Address)
	client.Debug(false)

	res, err := client.C.R().Get(URL)
	if err != nil {
		logrus.Errorf("GetAListOfGames failed: %v", err)
		return nil, err
	}

	// fmt.Println(string(res.Body()))
	set := NewGameSet()
	if err := json.Unmarshal(res.Body(), set); err != nil {
		logrus.Errorf("GetAListOfGames failed: %v", err)
		return nil, err
	}
	return set, nil
}

func GetGameByPackageName(packageName string) (*Game, error) {
	set, err := GetAListOfGames()
	// logrus.Infof("set: %v", set)
	if err != nil {
		logrus.Errorf("GetGameByPackageName failed: %v", err)
		return nil, err
	}

	for _, game := range set.GameItemInfo {
		// logrus.Infof("game.PackageName: %s", game.PackageName)
		if game.PackageName == packageName {
			return game, nil
		}
	}
	return nil, nil
}

func InstallGame(packageName string) error {
	game, err := GetGameByPackageName(packageName)
	if err != nil {
		logrus.Errorf("InstallGame failed: %v", err)
		return err
	}

	if game == nil {
		logrus.Errorf("InstallGame failed: game is nil")
		return err
	}
	// pm install --uid 10000 -r com.aligames.sgzzqb.mi
	cmd := []string{fmt.Sprintf("pm install --uid %d -r %s",
		game.WithUidM1().GetUid(), packageName)}

	// result := common.RunCommand(common.SH, cmd, 120*time.Second)
	logrus.Infof("cmd: %v", cmd)
	return nil
}
